package cn.dapeng.array;

import cn.dapeng.sort.InsertSort;
import cn.dapeng.utils.BuilderArray;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.array
 * @Description 给一个有序的数组
 * 1. 求>=target 左侧最小的下标
 * 2. 求<=target 右侧最大的下标
 * <p>
 * 思路：关注answer探针的变化
 * @ClassName BSNearLeftOrRight
 * @Author xupenghong
 * @Date 2024/9/6 13:28
 * @Version 1.0.0
 */
public class BSNearLeftOrRight {

    /**
     * 求>=target 左侧最小的下标
     *
     * @param array
     * @param target
     * @return
     */
    public static int nearestLeftNoGetterThanIndex(int[] array, int target) {
        if (array == null || array.length == 0) {
            return -1;
        }

        int left = 0, right = array.length - 1, answer = -1;

        while (left <= right) {
            int middle = (left + right) / 2;
            if (array[middle] >= target) {
                answer = middle;
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }

        return answer;
    }


    public static int testNearLeftNoGetterThanIndex(int[] array, int target) {
        if (array == null || array.length == 0) {
            return -1;
        }
        for (int i = 0; i < array.length; i++) {
            if (array[i] >= target) {
                return i;
            }
        }
        return -1;
    }


    public static int nearestRightNoGetterThanIndex(int[] array, int target) {
        if (array == null || array.length == 0) {
            return -1;
        }
        int left = 0, right = array.length - 1, answer = -1;

        while (left <= right) {
            int middle = (left + right) / 2;
            if (array[middle] <= target) {
                answer = middle;
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }
        return answer;
    }

    public static int testNearRightNoGetterThanIndex(int[] array, int target) {

        if (array == null || array.length == 0) {
            return -1;
        }

        for (int i = array.length - 1; i >= 0; i--) {
            if (array[i] <= target) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int testTimes = 100_0000;

        for (int i = 0; i < testTimes; i++) {

            int[] array = BuilderArray.builderArray(100, 20);
            InsertSort.sort(array);
            int target = (int) (Math.random() * 20);

//            if (nearestLeftNoGetterThanIndex(array, target) != testNearLeftNoGetterThanIndex(array, target)) {
//                System.out.println("Oops");
//                break;
//            }

            if (nearestRightNoGetterThanIndex(array, target) != testNearRightNoGetterThanIndex(array, target)) {
                System.out.println("Oops");
            }
        }
    }

}
